package com.hx.zhg.service.system.common;

import com.hx.zhg.exception.BusinessException;
import com.hx.zhg.service.system.vo.JSSDKConfigVo;
import com.hx.zhg.util.SHA1Util;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Random;

/**
 * Created by zhenghegong on 2020/4/19.
 */
public class WxSystemCommon {

    /**
     * 校验微信Signature
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param token
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
        try {
            Assert.notNull(signature);
            Assert.notNull(timestamp);
            Assert.notNull(nonce);
            Assert.notNull(token);
            String[] array = {token, timestamp, nonce};
            Arrays.sort(array);
            String arrayStr = String.join("", array);
            String hexStr = SHA1Util.encrypt(arrayStr);
            if (hexStr.toString().equals(signature)) {
                return true;
            }
        } catch (Exception e) {
            throw new BusinessException(String.format("signature校验异常; Exception: %s", e.getMessage()));
        }
        return false;
    }

    /**
     * 设置JSSDKConfig
     *
     * @param modelMap
     * @param jssdkConfigVo
     */
    public static void setJSSDKConfig(ModelMap modelMap, JSSDKConfigVo jssdkConfigVo) {
        modelMap.put("appId", jssdkConfigVo.getAppId());
        modelMap.put("timestamp", jssdkConfigVo.getTimestamp());
        modelMap.put("nonceStr", jssdkConfigVo.getNonceStr());
        modelMap.put("signature", jssdkConfigVo.getSignature());
    }

    /**
     * 生成随机 字符串
     *
     * @return
     */
    public static String generate(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
